package listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.*;

@WebListener()
public class Listener implements HttpSessionListener{
    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {//新建一个会话时候触发也可以说是客户端第一次和服务器交互时候触发
//        Object o=httpSessionEvent.getSession();
//        System.out.println("====>"+o);
        HttpSession session=httpSessionEvent.getSession();
        ServletContext context=session.getServletContext();//获取上下文
        Integer count=(Integer)context.getAttribute("count");
        if (count==null) {
            context.setAttribute("count",1);
        }
        else {
            System.out.println("访问人数"+count);
            context.setAttribute("count",count+1);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {//销毁会话的时候  一般来说只有某个按钮触发进行销毁 或者配置定时销毁
        System.out.println("销毁");
    }
}
